<?php

/**
 *    卖家限时促销控制器
 *
 *    @author    yanghj
 *    @date      2014.04.30
 */
class My_promotionApp extends StoreadminbaseApp
{
    var $_user_id;
    var $_activity_mod;
    var $_activity_goods_mod;
    var $_goods_mod;
    var $_cart_mod;
    var $_max_munber = 5;

    /* 构造函数 */

    function __construct()
    {
        $this->My_promotionApp();
    }

    function My_promotionApp()
    {
        parent::__construct();

        $this->_user_id = intval($this->visitor->get('user_id'));
        $this->_activity_mod = & m('activity');
        $this->_activity_goods_mod = & m('activitygoods');
        $this->_goods_mod = & m('goods');
        $this->_cart_mod = & m('cart');
    }
    
    /**
     *    活动列表
     *
     */   
    function index()
    {
        /* 取得列表数据 */
        $activity = $this->_activity_mod->find(array(
            'conditions'    => "store_id = " . $this->_user_id . " AND act_type = 1",
            'order'         => "act_id DESC",
        ));

        if($activity)
        {

            $act_ids = array_keys($activity);
            $sql="SELECT act_id,COUNT(goods_id) as quantity  FROM {$this->_activity_goods_mod->table} WHERE  act_id". db_create_in($act_ids)." GROUP BY act_id ";
            $temp = array();
            $activity_goods = $this->_activity_goods_mod->getAll($sql);
            foreach($activity_goods AS $val)
            {
                $temp[$val['act_id']] = $val['quantity'];
            }
            foreach($activity as $key=>$val)
            {
                $activity[$key]['validity'] = ceil(($activity[$key]['end_time'] - $activity[$key]['start_time'])/3600);
                $activity[$key]['goods_quantity'] = $temp[$key];
                if(gmtime() < $activity[$key]['start_time'])
                {
                    $activity[$key]['act_status'] = '未开始';
                }
                if(gmtime() >= $activity[$key]['start_time'] &&  gmtime() <= $activity[$key]['end_time'])
                {
                    $activity[$key]['act_status'] = '已开始';
                }
                if(gmtime() > $activity[$key]['end_time'])
                {
                    $activity[$key]['act_status'] = '已结束';
                }
            }

        }

        $this->assign('activity_munber', $this->_max_munber-count($activity));
        $this->assign('activity_list', $activity);

        /* 当前位置 */
        $this->_curlocal(LANG::get('seller_center'),    'index.php?app=seller',
                         LANG::get('my_marketing'), 'index.php?app=my_promotion',
                         LANG::get('my_promotion'));

        /* 当前用户中心菜单 */
        $this->_curitem('my_promotion');

        /* 当前所处子菜单 */
        $this->_curmenu('my_marketing');
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_promotion'));
        $this->display('my_promotion.index.html');
    }


    /**
     *    添加活动
     *
     */
    function add()
    {
        if (!IS_POST)
        {
            $activity = array(
                'act_name' => '限时促销',
                'discount_type' => '1',
            );
            /* 当前位置 */
            $this->_curlocal(LANG::get('seller_center'),    'index.php?app=seller',
                LANG::get('my_marketing'), 'index.php?app=my_promotion',
                LANG::get('my_promotion'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_promotion');

            /* 当前所处子菜单 */
            $this->_curmenu('my_marketing');
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js',
            ));
            $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_promotion'));
            $this->assign('sgcategories', $this->_get_sgcategory_options());//取得店铺商品分类
            $this->assign('ajax_goods', ecm_json_encode($this->_get_goods()));//取得没有参与活动的商品
            $this->assign('activity', $activity); //活动数据
            $this->assign('act_names', array('a'=>'限时促销','b'=>'厂家直供','c'=>'限量爆款','d'=>'清仓特卖','e'=>'最新上架'));
            $this->display('my_promotion.form.html');

        }
        else
        {
            /* 取得数据 */
            $data = $this->_get_post_data(0);
            if(empty($data))
            {
                $this->show_warning('添加的商品不能超过20个');
                return;
            }
            /* 检查数据 */
            if (!$this->_check_post_data($data, 0))
            {
                $this->show_warning($this->get_error());
                return;
            }

            /* 保存数据 */
            if (!$this->_save_post_data($data, 0))
            {
                $this->show_warning($this->get_error());
                return;
            }
            $this->show_message('添加活动成功', 'back_list', 'index.php?app=my_promotion');
        }
    }
    
    /**
     *    编辑活动
     *
     */
    function edit()
    {
        $act_id = empty($_GET['act_id']) ? 0 : intval($_GET['act_id']);
        if(empty($act_id))
        {
            $this->show_warning('没有相关的活动');
            return;
        }
        $activity = $this->_activity_mod->get_info($act_id);
        if(empty($activity))
        {
            $this->show_warning('没有相关的活动');
            return;
        }

        if (!IS_POST)
        {

            $spec_table  = DB_PREFIX . 'goods_spec';
            $sql = "SELECT a.id,a.promote_quantity,a.promote_discount,a.promote_price,g.goods_name,g.default_image,g.goods_id,g.price_type,stock FROM {$this->_activity_goods_mod->table} AS a left join (SELECT goods_id, SUM(stock) as stock FROM {$spec_table} group by goods_id) s on a.goods_id = s.goods_id left join {$this->_goods_mod->table} AS g on a.goods_id = g.goods_id  WHERE a.act_id = {$act_id}";

            $goods_list = $this->_goods_mod->getAll($sql);
            if($goods_list)
            {
                foreach($goods_list as $key => $val)
                {
                    $price_interval = $this->_goods_mod->get_price_interval($val['goods_id'], $val['price_type']);
                    $goods_list[$key]['goods_url'] = SITE_URL.'/'.url('app=goods&id='.$val['goods_id']);
                    $goods_list[$key]['promote_discount'] = $val['promote_discount']*10;
                    if(isset($price_interval['price']))
                    {
                        $goods_list[$key]['price'] = $price_interval['price'];
                        $goods_list[$key]['discount_price'] = sprintf("%.2f",$price_interval['price']*$val['promote_discount']);
                        $goods_list[$key]['is_district'] = 0;
                    }
                    if(isset($price_interval['min_price']))
                    {
                        $goods_list[$key]['min_price'] = $price_interval['min_price'];
                        $goods_list[$key]['max_price'] = $price_interval['max_price'];
                        $goods_list[$key]['min_discount_price'] = sprintf("%.2f",$price_interval['min_price']*$val['promote_discount']);
                        $goods_list[$key]['max_discount_price'] = sprintf("%.2f",$price_interval['max_price']*$val['promote_discount']);
                        $goods_list[$key]['is_district'] = 1;
                    }
                }
            }


            /* 当前位置 */
            $this->_curlocal(LANG::get('seller_center'),    'index.php?app=seller',
                LANG::get('my_marketing'), 'index.php?app=my_promotion',
                LANG::get('my_promotion'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_promotion');

            /* 当前所处子菜单 */
            $this->_curmenu('my_marketing');
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js',
            ));
            $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_promotion'));
            $this->assign('activity', $activity); //活动数据
            $this->assign('goods_list', $goods_list); //关联活动商品
            $this->assign('sgcategories', $this->_get_sgcategory_options());//取得店铺商品分类
            $this->assign('ajax_goods', ecm_json_encode($this->_get_goods()));//取得没有参与活动的商品
            $this->assign('act_names', array('a'=>'限时促销','b'=>'厂家直供','c'=>'限量爆款','d'=>'清仓特卖','e'=>'最新上架'));
            $this->display('my_promotion.form.html');
        }
        else
        {
            /* 取得数据 */
            $data = $this->_get_post_data($act_id,$activity['start_time'],$activity['end_time']);
            if(empty($data))
            {
                $this->show_warning('添加的商品不能超过20个');
                return;
            }
            /* 检查数据 */
            if (!$this->_check_post_data($data, $act_id))
            {
                $this->show_warning($this->get_error());
                return;
            }

            /* 保存数据 */
            if (!$this->_save_post_data($data, $act_id))
            {
                $this->show_warning($this->get_error());
                return;
            }
            $this->show_message('修改活动成功', 'back_list', 'index.php?app=my_promotion');
        }
    }

    /**
     *    删除活动
     *
     */
    function drop()
    {
        $act_id = empty($_GET['act_id']) ? 0 : intval($_GET['act_id']);
        if (!$act_id)
        {
            $this->show_warning("该活动不存在");
            return ;
        }
        $ids  = $this->_activity_goods_mod->getCol("SELECT id FROM {$this->_activity_goods_mod->table} WHERE act_id = {$act_id}");

        if($ids)
        {
            foreach($ids as $id)
            {
                $this->_drop_goods($id);
            }
        }

        if (!$this->_activity_mod->db->query("DELETE FROM {$this->_activity_mod->table} WHERE act_id = {$act_id}"))
        {
            $this->show_warning("删除活动失败");
            return ;
        }

        $this->show_message("删除活动成功");
    }
    

    /* AJAX请求还没有参与活动的商品 */
    function ajax_get_goods()
    {
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        $goods_name = empty($_GET['goods_name']) ? '' : html_script($_GET['goods_name']);
        $goods_data = $this->_get_goods($cate_id, $goods_name);

        if(is_array($goods_data))
        {
            echo ecm_json_encode($goods_data);
            exit;
        }
        else
        {
            echo ecm_json_encode(false);
            exit;
        }


    }

    /* AJAX删除参与活动的商品 */
    function ajax_dorp_goods()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if(!$id)
        {
            echo ecm_json_encode(false);
            exit;
        }

        $rs = $this->_drop_goods($id);
        echo ecm_json_encode($rs);
        exit;

    }

    /**
     *    删除活动关联的商品
     *
     */
    function _drop_goods($id)
    {
        $now = gmtime();
        if (!$id)
        {
            return false;
        }
        $promotion     = $this->_activity_goods_mod->get_info($id);

        if (empty($promotion))
        {
            return false;
        }

        $activity     = $this->_activity_mod->get_info($promotion['act_id']);
        $this->_goods_mod->edit($promotion['goods_id'], array('promote_price'=>0,'act_id'=>0));//更新商品的数据
        if ($this->_goods_mod->has_error())
        {
            return false;
        }
        //如果是在活动已经开始则更新购物车的数据
        if($now > $activity['start_time'] && $now < $activity['end_time'])
        {
            $sql = "SELECT c.rec_id,c.goods_id,c.price,c.retail_price,g.act_id,g.goods_id,g.promote_discount,g.promote_price,go.shipping_id FROM {$this->_cart_mod->table} AS c left join {$this->_activity_goods_mod->table} AS g on c.goods_id = g.goods_id left join {$this->_goods_mod->table} AS go on c.goods_id = go.goods_id  WHERE c.goods_id = {$promotion['goods_id']}";
            $end_goods = $this->_cart_mod->getAll($sql);
            if($end_goods)
            {
                foreach($end_goods as $key=>$val)
                {
                    $cart_data['price'] = $val['retail_price'];//还原商品价格
                    if($activity['free_shipping'] == 1)
                    {
                        $cart_data['shipping_id'] = $val['shipping_id'];//如果是包邮优惠,则还原商品运费ID的值
                    }
                    $this->_cart_mod->edit($val['rec_id'], $cart_data);//更新购物车的数据
                    if ($this->_cart_mod->has_error())
                    {
                        return false;
                    }
                }
            }

        }
        if (!$this->_activity_goods_mod->drop($id))
        {
            return false;
        }
        return true;
    }

    /**
     * 检查提交的数据
     */
    function _check_post_data($data, $act_id = 0)
    {

        if (empty($data['activity']['act_name']))
        {
            $this->_error('活动名称不能为空');
            return false;
        }
        if (empty($data['activity']['start_time']) || empty($data['activity']['end_time']))
        {
            $this->_error('请选择活动时间');
            return false;
        }
        if (empty($data['activity']['discount_type']) && empty($data['activity']['free_shipping']))
        {
            $this->_error('请选择优惠方式');
            return false;
        }

        if($data['activity']['discount_type'] == 1)
        {
            foreach($data['activity_goods'] as $key => $val)
            {
                if($val['promote_discount'] <= 0 || $val['promote_discount'] >= 1)
                {
                    $this->_error('限时折扣填写错误,');
                    return false;
                }
            }
        }


        return true;
    }

    /**
     * 提交的数据
     */
    function _get_post_data($act_id = 0,$start_time = 0, $end_time = 0)
    {
        $now = gmtime();
        $cart_data = array();
        $activity = array(
            'act_name' => html_script(trim($_POST['act_name'])),
            'act_desc' => html_script(trim($_POST['act_desc'])),
            'store_id' => $this->_user_id,
            'start_time' => $start_time > 0 ? $start_time : gmstr2time(trim($_POST['start_time']).':00'),
            'end_time' => gmstr2time(trim($_POST['end_time']).':00'),
            'act_type' => 1,
            'discount_type' => isset($_POST['discount_type']) ? intval($_POST['discount_type']) : 0,
            'free_shipping' => isset($_POST['free_shipping']) ? intval($_POST['free_shipping']) : 0,
        );

        $goods_id_arr = $_POST['goods_id'];
        $id_arr = $_POST['id'];
        $price_arr = $_POST['price'];
        $promote_discount_arr = $_POST['promote_discount'];
        $promote_price_arr = $_POST['promote_price'];
        $promote_quantity_arr = $_POST['promote_quantity'];
        if(!is_array($goods_id_arr) && count($goods_id_arr) > 20)
        {
            return false;
        }
        foreach($goods_id_arr as $key=>$goods_id)
        {
            $goods[$key] = array(
                'goods_id' => $goods_id,
                'promote_price' => $activity['discount_type'] == 2 ? $this->_filter_price($promote_price_arr[$key]) : $this->_filter_price($price_arr[$key]*$promote_discount_arr[$key]/10),
            );

            if (($id = intval($id_arr[$key]))) // 已有活动商品
            {
                $activity_goods[$key] = array(
                    'id' => $id,
                    'act_type' => 1,
                    'goods_id' => $goods_id,
                    'promote_quantity' => isset($promote_quantity_arr[$key]) ? intval($promote_quantity_arr[$key]) : 0,
                    'promote_discount' => isset($promote_discount_arr[$key]) ? floatval($promote_discount_arr[$key]/10) : 0,
                    'promote_price' => isset($promote_price_arr[$key]) ? $this->_filter_price($promote_price_arr[$key]) : 0,
                );
            }
            else  // 新增的活动商品
            {
                $activity_goods[$key] = array(
                    'act_type' => 1,
                    'goods_id' => $goods_id,
                    'promote_quantity' => isset($promote_quantity_arr[$key]) ? intval($promote_quantity_arr[$key]) : 0,
                    'promote_discount' => isset($promote_discount_arr[$key]) ? floatval($promote_discount_arr[$key]/10) : 0,
                    'promote_price' => isset($promote_price_arr[$key]) ? $this->_filter_price($promote_price_arr[$key]) : 0,
                );
            }
        }
        //修改活动的时候,如果活动时间是从原来已经结束修改为已经开始或者添加的时候活动已经开始
        if(($act_id > 0 && $now > $end_time && $now < $activity['end_time']) || ($act_id == 0 && $now > $activity['start_time'] && $now < $activity['end_time'] ))
        {
            $sql = "SELECT c.rec_id,c.goods_id,c.price,c.retail_price,g.act_id,g.goods_id,g.promote_discount,g.promote_price FROM {$this->_cart_mod->table} AS c left join {$this->_activity_goods_mod->table} AS g on c.goods_id = g.goods_id  WHERE g.act_id ={$act_id}";

            $start_goods = $this->_cart_mod->getAll($sql);
            if($start_goods)
            {
                foreach($start_goods as $key=>$val)
                {
                    if($val['promote_discount']>0)
                    {
                        $cart_data[$val['rec_id']]['price'] = $val['retail_price']*$val['promote_discount'];//如果是打折优惠,则商品价格=原价格*折扣
                    }
                    if($val['promote_price']>0)
                    {
                        $cart_data[$val['rec_id']]['price'] = $val['promote_price'];//如果是一口价优惠,则商品价格=一口价
                    }
                    if($activity['free_shipping'] == 1)
                    {
                        $cart_data[$val['rec_id']]['shipping_id'] = 0;//如果是包邮优惠,则运费ID为0
                    }
                }
            }
            $activity['act_status'] = 1;
        }

        return array('activity' => $activity, 'goods' => $goods, 'activity_goods' => $activity_goods, 'cart' => $cart_data);
    }

    /**
     * 保存数据
     */
    function _save_post_data($data, $act_id = 0)
    {
        if($act_id > 0)
        {

            //修改活动信息
            $this->_activity_mod->edit($act_id, $data['activity']);
            if ($this->_activity_mod->get_error())
            {
                $this->_error($this->_activity_mod->get_error());
                return false;
            }
        }
        else
        {
            //保存活动信息
            $act_id = $this->_activity_mod->add($data['activity']);
            if (!$act_id)
            {
                $this->_error($this->_activity_mod->get_error());
                return false;
            }
        }
        //保存活动的商品
        foreach ($data['activity_goods'] as $key => $activity)
        {
            $activity['act_id'] = $act_id;
            if ($id = $activity['id']) // 更新已有活动商品ID
            {
                $this->_activity_goods_mod->edit($id, $activity);
                if ($this->_activity_goods_mod->get_error())
                {
                    $this->_error($this->_activity_goods_mod->get_error());
                    return false;
                }
            }
            else // 新加活动商品ID
            {
                $id = $this->_activity_goods_mod->add($activity);
                if (!$id)
                {
                    $this->_error($this->_activity_goods_mod->get_error());
                    return false;
                }
            }
        }
        //保存关联的商品
        foreach ($data['goods'] as $key => $val)
        {
            $goods['promote_price'] = $val['promote_price'];
            $goods['act_id'] = $act_id;

            $this->_goods_mod->edit($val['goods_id'], $goods);
            if ($this->_goods_mod->get_error())
            {
                $this->_error($this->_goods_mod->get_error());
                return false;
            }
        }

        //更新购物车的商品
        if(is_array($data['cart']))
        {
            foreach ($data['cart'] as $rec_id => $cart)
            {
                $this->_cart_mod->edit($rec_id, $cart);
                if ($this->_cart_mod->get_error())
                {
                    $this->_error($this->_cart_mod->get_error());
                    return false;
                }
            }
        }

        return true;
    }


    /**
     * 取得没有参加活动商品
     */
    function _get_goods($cate_id = 0, $goods_name = '')
    {
        $conditions = "g.closed = 0 AND g.if_show = 1 AND g.act_id = 0 AND g.store_id = " . $this->_user_id;
        $gcategory_mod =& bm('gcategory', array('_store_id' => $this->_store_id));
        $category_table  = DB_PREFIX . 'category_goods';
        $spec_table  = DB_PREFIX . 'goods_spec';
        $temp = array();
        if($cate_id > 0)
        {
            $cate_ids = $gcategory_mod->get_descendant_ids($cate_id);
            $sql = "SELECT DISTINCT goods_id FROM {$category_table} WHERE cate_id " . db_create_in($cate_ids);
            $goods_ids = $this->_goods_mod->getCol($sql);
            $conditions .= " AND g.goods_id " . db_create_in($goods_ids);
        }
        if(!empty($goods_name))
        {
            $conditions .= " AND g.goods_name LIKE '%{$goods_name}%'";
        }

        $sql = "SELECT g.goods_name,g.default_image,g.goods_id,g.price_type,stock FROM {$this->_goods_mod->table} AS g left join (SELECT goods_id, SUM(stock) as stock FROM {$spec_table} group by goods_id) s on g.goods_id = s.goods_id WHERE {$conditions}";

        $arr = $this->_goods_mod->getAll($sql);
        if($arr)
        {
            foreach($arr as $key => $val)
            {
                $price_interval = $this->_goods_mod->get_price_interval($val['goods_id'], $val['price_type']);
                $arr[$key]['goods_url'] = SITE_URL.'/'.url('app=goods&id='.$val['goods_id']);
                if(isset($price_interval['price']))
                {
                    $arr[$key]['price'] = $price_interval['price'];
                    $arr[$key]['is_district'] = 0;
                }
                if(isset($price_interval['min_price']))
                {
                    $arr[$key]['min_price'] = $price_interval['min_price'];
                    $arr[$key]['max_price'] = $price_interval['max_price'];
                    $arr[$key]['is_district'] = 1;
                }
            }

            foreach($arr as $goods)
            {
                $temp[$goods['goods_id']] = $goods;
            }
        }

        return $temp;
    }

    /* 价格过滤，返回非负浮点数 */

    function _filter_price($price)
    {
        return abs(floatval($price));
    }

    /* 取得本店所有商品分类 */

    function _get_sgcategory_options()
    {
        $mod = & bm('gcategory', array('_store_id' => $this->_user_id));
        $gcategories = $mod->get_list();
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getOptions();
    }

}

?>